package com.marion.study.controller;

import com.marion.study.aop.pattern.dynamicproxy.CglibDynamicProxy;
import com.marion.study.aop.pattern.dynamicproxy.JdkDynamicProxy;
import com.marion.study.aop.pattern.staticproxy.Image;
import com.marion.study.aop.pattern.staticproxy.ProxyImage;
import com.marion.study.aop.pattern.staticproxy.RealImage;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Proxy;

@RestController
@RequestMapping("/")
public class AopController {

    /**
     * 静态代理
     */
    @GetMapping("/proxy/static")
    public Object staticProxy() {

        /**
         * 1. 3种角色定义，代理类、目标类、抽象接口
         * 2. 定义抽象接口
         * 3. 定义目标类
         * 4. 定义代理类
         * 5. 调用代理类
         */

        ProxyImage proxyImage = new ProxyImage("static");
        proxyImage.display();
        proxyImage.draw();

        return null;
    }

    /**
     * JDK动态代理
     */
    @GetMapping("/proxy/dynamic/jdk")
    public Object JdkDynamicProxy() {

        /**
         * 1. 定义JDK动态代理类
         * 2. Proxy调用
         */

        Image jdk = (Image) Proxy.newProxyInstance(AopController.class.getClassLoader(),
                new Class[]{Image.class},
                new JdkDynamicProxy(new RealImage("jdk")));
        jdk.display();
        jdk.draw();

        return null;
    }

    /**
     * Cglib动态代理
     */
    @GetMapping("/proxy/dynamic/cglib")
    public Object cglibDynamicProxy() {

        /**
         * 1. 定义Cglib动态代理，通过继承方式
         * 2. 通过Enhancer调用
         */

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(RealImage.class);
        enhancer.setCallback(new CglibDynamicProxy());
        Image o = (Image) enhancer.create();
        o.display();
        o.draw();

        return null;

    }

}
